package com.ctrl.riveradministrator;

import static com.ctrl.riveradministrator.common.Constants.BASE_URL;
import static com.ctrl.riveradministrator.mvp.presenter.MainPresenter.getVersionCode;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.ctrl.riveradministrator.R;
import com.ctrl.riveradministrator.base.BaseActivity;
import com.ctrl.riveradministrator.mvp.model.Succeed;
import com.ctrl.riveradministrator.mvp.model.Version;
import com.ctrl.riveradministrator.mvp.presenter.MainPresenter;
import com.ctrl.riveradministrator.mvp.view.activity.main.HomeFragment;
import com.ctrl.riveradministrator.mvp.view.activity.main.MainView;
import com.ctrl.riveradministrator.mvp.view.activity.work_bench.WorkBenchFragment;
import com.ctrl.riveradministrator.mvp.view.fragment.UserFragment;
import com.ctrl.riveradministrator.util.CommonUtil;
import com.yanzhenjie.kalle.Headers;
import com.yanzhenjie.kalle.JsonBody;
import com.yanzhenjie.kalle.Kalle;
import com.yanzhenjie.kalle.simple.SimpleCallback;
import com.yanzhenjie.kalle.simple.SimpleResponse;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class MainActivity
        extends BaseActivity<MainPresenter>
        implements MainView, TabLayout.OnTabSelectedListener {

    private List<Fragment> fragments;
    private TabLayout tabLayout;

    /**
     * 两次点击的间隔时间
     */
    private long waitTime = 1000;
    private long touchTime = 0;


    @Override
    protected void initParams(Bundle parms) {

    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_main;
    }


    @Override
    protected void initView(View view) {
        getWindow().getDecorView()
                .setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        tabLayout = $(R.id.navi_tab);
        /*
         * 初始化底部导航栏
         * */
        tabLayout.addTab(tabLayout.newTab().setText("首页").setIcon(R.drawable.ic_home));
        tabLayout.addTab(tabLayout.newTab().setText("工作台").setIcon(R.drawable.ic_other));
        tabLayout.addTab(tabLayout.newTab().setText("个人中心").setIcon(R.drawable.ic_mine));
        /*
         * 设置底部导航栏自定义布局，拉近TITLE与ICON距离
         * */
        Objects.requireNonNull(tabLayout.getTabAt(0)).setCustomView(getTabView("首页", R.drawable.ic_home_unselect));
        Objects.requireNonNull(tabLayout.getTabAt(1)).setCustomView(getTabView("工作台", R.drawable.ic_other_unselect));
        Objects.requireNonNull(tabLayout.getTabAt(2)).setCustomView(getTabView("个人中心", R.drawable.ic_mine_unselect));
        changeTabSelect(Objects.requireNonNull(tabLayout.getTabAt(0)));//默认选中第一个
        /*
         * 填充fragment
         * */
        fragments = new ArrayList<>();
        fragments.add(new HomeFragment());
        fragments.add(new WorkBenchFragment());
        fragments.add(new UserFragment());
        switchFragment(fragments.get(0), R.id.content_rl).commit();//第一个显示的界面

        String s = CommonUtil.sHA1(this);
        Log.i(TAG, "initView: " + s);
    }

    @Override
    protected void doBusiness(Context mContext) {
//        mPresenter.checkUpdate();
        getVersion();
    }

    @Override
    protected void widgetClick(View view) {

    }

    @Override
    protected void setListener() {
        tabLayout.addOnTabSelectedListener(this);
    }

    @Override
    public void handleMessage(Message message, int what) {

    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter(this);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void onBackPressed() {

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 两次返回键，退出程序
        if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {
            long currentTime = System.currentTimeMillis();
            if ((currentTime - touchTime) >= waitTime) {
                Toast.makeText(this, "再按一次退应用", Toast.LENGTH_SHORT).show();
                touchTime = currentTime;
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        switchFragment(fragments.get(tab.getPosition()), R.id.content_rl).commit();
        changeTabSelect(tab);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        changeTabNormal(tab);
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    /**
     * 获取设置的底部导航栏ITEM
     *
     * @param title    标题
     * @param imageSrc 图标
     * @return View用于setCustomView
     */
    private View getTabView(String title, int imageSrc) {
        View v = LayoutInflater.from(getApplicationContext()).inflate(R.layout.menu_navi_view, null);
        TextView textView = v.findViewById(R.id.tv);
        textView.setText(title);
        ImageView imageView = v.findViewById(R.id.iv);
        imageView.setImageResource(imageSrc);
        return v;
    }

    /**
     * 设置选中时状态
     *
     * @param tab 底部导航栏ITEM
     */
    private void changeTabSelect(TabLayout.Tab tab) {
        View view = tab.getCustomView();
        ImageView iconTv = view.findViewById(R.id.iv);
        TextView titleTv = view.findViewById(R.id.tv);
        titleTv.setTextColor(getResources().getColor(R.color.colorPrimary));
        if (titleTv.getText().toString().equals("首页")) {
            iconTv.setImageResource(R.drawable.ic_home);
        } else if (titleTv.getText().toString().equals("工作台")) {
            iconTv.setImageResource(R.drawable.ic_other);
        } else if (titleTv.getText().toString().equals("个人中心")) {
            iconTv.setImageResource(R.drawable.ic_mine);
        }
    }

    /**
     * 设置未选中时状态
     *
     * @param tab
     */
    private void changeTabNormal(TabLayout.Tab tab) {
        View view = tab.getCustomView();
        ImageView iconTv = view.findViewById(R.id.iv);
        TextView titleTv = view.findViewById(R.id.tv);
        titleTv.setTextColor(getResources().getColor(R.color.theme_blue1));
        if (titleTv.getText().toString().equals("首页")) {
            iconTv.setImageResource(R.drawable.ic_home_unselect);
        } else if (titleTv.getText().toString().equals("工作台")) {
            iconTv.setImageResource(R.drawable.ic_other_unselect);
        } else if (titleTv.getText().toString().equals("个人中心")) {
            iconTv.setImageResource(R.drawable.ic_mine_unselect);
        }
    }

    @Override
    public void onCheckVersion(String version, String describe, String fileName, boolean isForce) {
        showUpdateVersionDialog(version, describe, fileName);
    }

    @Override
    public void onFailed(String msg) {

    }

    /**
     * 显示升级提示
     */
    private void showUpdateVersionDialog(String version, String describe, String fileName) {
        new AlertDialog.Builder(this)
                .setTitle(version)
                .setMessage(describe)
                // 更新
                .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri uri = Uri.parse(BASE_URL + fileName);
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                    }
                })
                .setNegativeButton("稍后升级", null).show();
    }


    private void getVersion() {

        Headers headers = new Headers();
        headers.add("content-type", "application/json");
        Kalle.
            get(BASE_URL + "file/apk/getVersion").
            tag(this).
            perform(new SimpleCallback<String>() {

                @Override
                public void onResponse(SimpleResponse<String, String> response) {
                    //返回消息
                    if (response.isSucceed()){
                        Succeed succeed = JSON.parseObject(response.succeed(), Succeed.class);

                        if (200 == succeed.getCode()){

                            Version version =  JSON.parseObject(succeed.getData(), Version.class);
                            int versionCode = version.getAppVersionNo();
                            String appVersion = version.getAppVersion();
                            String fileName = version.getFileName();
                            boolean force = version.isForce();
                            String appUpdateDescription = version.getAppUpdateDescription();
                            if (getVersionCode(RaApplication.raApplication.getApplicationContext()) != versionCode) {
                                onCheckVersion(appVersion, appUpdateDescription, fileName, force);
                            }
                        }
                    }else {
                        onFailed("更新检查失败");
                    }

                }
            });
    }
}
